<template>
  <el-container style="margin-top: -20px;background-color:#ffffff;" >
    <el-aside width="210px" style="margin-top: 20px">
      <el-button-group>
        <el-button type="primary" @click="showSaveNewsType">添加</el-button>
        <el-button type="warning" @click="showEditNewsType">编辑</el-button>
        <el-button type="danger" @click="removeNewsType">删除</el-button>
      </el-button-group>
      <vxe-table
              ref="xTable1"
              @radio-change="radioChange"
              :show-header="false"
              :data="tableData"
              :row-config="{keyField: 'id'}"
              :radio-config="{labelField: 'newsTypeName',checkRowKey: checkRowKey,highlight: true}">
        <vxe-column type="radio"></vxe-column>
      </vxe-table>
    </el-aside>
    <el-main style="padding: 0 15px;background-color:#ffffff;min-height: 500px;">
      <el-row>
        <el-col>
          <el-form :inline="true" :model="formInline" size="small">
            <el-form-item label="关键字">
              <el-input v-model="formInline.keyword" placeholder="关键字"></el-input>
            </el-form-item>
            <el-form-item label="发布时间">
              <el-date-picker
                      v-model="formInline.periodOfTime"
                      value-format="yyyy-MM-dd"
                      type="daterange"
                      unlink-panels
                      range-separator="-"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                      :picker-options="pickerOptions">
              </el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button type="success" @click="clickSelect">查询</el-button>
              <el-button type="primary" @click="toNewsAdd">发布</el-button>
            </el-form-item>
          </el-form>

          <ul class="news-ul">
            <li class="news-list" v-for="item of newsList">
              <p>
                <span class="news-title" @click="toNewsManageDetail(item.nid)">{{item.newsTitle}}</span>
                <span class="news-time">{{item.createdTime}}</span>
              </p>
              <p class="news-def">
            <span class="news-org">
              发布人： <span v-if="item.createdUser">{{item.createdUser.userName}}</span><span v-else>????????</span>
            </span>
                <span class="news-eye-star"><i class="fa fa-eye"></i>{{item.lookNum}}&emsp;<i class="fa fa-star"></i>{{item.collectNum}}</span>
              </p>
            </li>
          </ul>
          <vxe-pager
                  :current-page.sync="page.currentPage"
                  :page-size.sync="page.pageSize"
                  :total="page.total"
                  @page-change="handlePageChange"
                  :layouts="['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'FullJump', 'Total']">
          </vxe-pager>
        </el-col>
      </el-row>
    </el-main>

    <!--  添加，编辑新闻分类   -->
    <vxe-modal v-model="showNewsTypeModal" title="新闻分类" width="480">
      <template #default>
        <el-container>
          <el-main>
            <el-row>
              <el-col class="showNewsTypeModal">
                <el-form :model="newsType" :rules="newsTypeRules" ref="ruleForm" label-width="100px">
                  <el-form-item label="类型名称" prop="newsTypeName">
                    <el-input v-model="newsType.newsTypeName"></el-input>
                  </el-form-item>
                  <el-form-item label="排序" prop="seq">
                    <el-input-number v-model="newsType.seq" :min="1" :max="99" label="描述文字"></el-input-number>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="saveNewsType" v-if="isEdit">提交</el-button>
                    <el-button type="primary" @click="editNewsType" v-else>编辑</el-button>
                    <el-button @click="showNewsTypeModal = false"> 取消</el-button>
                  </el-form-item>
                </el-form>
              </el-col>
            </el-row>
          </el-main>
        </el-container>
      </template>
    </vxe-modal>
  </el-container>
</template>

<script>
  import pickerShortcut from "@/mixins/picker-shortcut";
  import {newTypeList, saveNewsType, editNewsType, removeNewsType, newList} from '@/api/operations-center/news'

  /**
   *{ 新闻管理列表 }
   * @param:
   * @author: 宋康
   * @DateTime: 2022/7/6
   */
  export default {
    name: "NewsManageList",
    mixins: [pickerShortcut],
    data() {
      return {
        showNewsTypeModal: false,
        isEdit: false,
        newsType: {
          newsTypeName: "",
          parentId: '0',
          seq: '1'
        },
        newsTypeRules: {
          newsTypeName: [
            {required: true, message: '请输入新闻分类名称', trigger: 'blur'},
            {min: 1, max: 30, message: '长度在 1 到 30 个字符', trigger: 'blur'}
          ],
          seq: [
            {required: true, message: '请输入排序', trigger: 'blur'},
          ],
        },
        checkRowKey: '-1',
        tableData: [],
        //
        formInline: {
          keyword: "",
          typeId: "0",
          startDate: "",
          endDate: "",
          periodOfTime: [],
        },
        page: {
          currentPage: 1,
          pageSize: 10,
          total: 0
        },
        newsList: []
      }
    },
    methods: {
      /**
       * {获取新闻分类}
       *
       * @author: 宋康
       * @date: 2022/8/24 11:40
       */
      queryNewTypeList() {
        newTypeList().then(res => {
          if (res.status) {
            let data = [];
            data.push({
              "id": "-1",
              "parentId": "0",
              "newsTypeName": "全部",
              "seq": 1
            })
            for (let d of res.data) {
              data.push(d)
            }
            this.tableData = data;
          }
        })
      },
      /**
       * {显示添加新闻分类窗口}
       *
       * @author: 宋康
       * @date: 2022/8/24 11:36
       */
      showSaveNewsType() {
        this.newsType = {
          newsTypeName: "",
          parentId: '0',
          seq: '1'
        }
        this.isEdit = true;
        this.showNewsTypeModal = true;
      },
      /**
       * {显示编辑新闻分类窗口}
       *
       * @author: 宋康
       * @date: 2022/8/24 16:24
       */
      showEditNewsType() {
        let radioRecord = this.$refs['xTable1'].getRadioRecord();
        if (radioRecord && '-1' !== radioRecord.id) {
          this.newsType = {
            ...radioRecord
          }
          this.isEdit = false;
          this.showNewsTypeModal = true;
        }
      },
      /**
       * {保存新闻分类}
       *
       * @author: 宋康
       * @date: 2022/8/24 14:43
       */
      saveNewsType() {
        this.$refs['ruleForm'].validate((valid) => {
          if (valid) {
            saveNewsType(this.newsType).then(res => {
              if (res.status) {
                this.$XModal.alert({
                  content: '添加成功',
                  status: 'success',
                }).then(() => {
                  this.showNewsTypeModal = false;
                  this.queryNewTypeList();
                })
              } else {
                this.$XModal.alert({
                  content: res['msg'],
                  status: 'error',
                })
              }
            })
          } else {
            return false;
          }
        });
      },
      /**
       * {编辑新闻分类}
       *
       * @author: 宋康
       * @date: 2022/8/24 16:40
       */
      editNewsType() {
        this.$refs['ruleForm'].validate((valid) => {
          if (valid) {
            editNewsType(this.newsType).then(res => {
              if (res.status) {
                this.$XModal.alert({
                  content: '编辑成功',
                  status: 'success',
                }).then(() => {
                  this.showNewsTypeModal = false;
                  this.queryNewTypeList();
                })
              } else {
                this.$XModal.alert({
                  content: res['msg'],
                  status: 'error',
                })
              }
            })
          } else {
            return false;
          }
        });
      },
      /**
       * {移除指定新闻分类}
       *
       * @author: 宋康
       * @date: 2022/8/25 09:59
       */
      removeNewsType() {
        let radioRecord = this.$refs['xTable1'].getRadioRecord();
        if (radioRecord && '-1' !== radioRecord.id) {
          this.$alert(`确定删除【${radioRecord.newsTypeName}】吗？`, '提示', {
            showCancelButton: true,
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            removeNewsType(radioRecord.id).then(res => {
              if (res.status) {
                this.$XModal.alert({
                  content: '删除成功',
                  status: 'success',
                }).then(() => {
                  this.checkRowKey = '-1';
                  this.radioChange({
                    newValue: {
                      id: '-1'
                    }
                  })
                  this.queryNewTypeList();
                })
              } else {
                this.$XModal.alert({
                  content: res['msg'],
                  status: 'error',
                })
              }
            })
          }).catch(() => {
          });
        }
      },
      /**
       * {新闻分类单选选中触发}
       *
       * @author: 宋康
       * @date: 2022/8/24 10:28
       */
      radioChange({newValue}) {
        this.$router.push({
          name: 'NewsManageList',
          query: {
            type: newValue.id
          }
        })
      },
      /**
       * {跳转新闻添加}
       *
       * @author: 宋康
       * @date: 2022/8/25 10:15
       */
      toNewsAdd() {
        this.$router.push({
          name: 'NewsManageAdd'
        })
      },
      /**
       *{ 跳转新闻详情 }
       * @param:
       * @author: 宋康
       * @DateTime: 2022/7/7
       */
      toNewsManageDetail(key) {
        this.$router.push({
          name: 'NewsManageDetail',
          query: {
            type: this.$route.query.type || '-1',
            id: key
          }
        })
      },
      /**
       * {获取新闻列表}
       *
       * @author: 宋康
       * @date: 2022/8/25 09:42
       */
      queryNewsList() {
        let type = this.$route.query.type || '-1';
        this.formInline.typeId = '-1' === type ? '0' : type;
        if (!this.formInline.periodOfTime) {
          this.formInline.periodOfTime = [];
        }
        this.formInline.startDate = this.formInline.periodOfTime[0] || '';
        this.formInline.endDate = this.formInline.periodOfTime[1] || '';
        newList(this.page.currentPage, this.page.pageSize, this.formInline).then(res => {
          if (res.status) {
            let data = res.data;
            this.page.total = data.total;
            this.newsList = data.records;
          }
        })
      },
      /**
       * {点击查询触发}
       *
       * @author: 宋康
       * @date: 2022/8/25 11:12
       */
      clickSelect() {
        this.page.currentPage = 1;
        this.queryNewsList();
      },
      /**
       * {分页}
       *
       * @author: 宋康
       * @date: 2022/8/25 11:17
       */
      handlePageChange({currentPage, pageSize}) {
        this.page.currentPage = currentPage;
        this.page.pageSize = pageSize;
        this.queryNewsList();
      }
    },
    mounted() {
      this.checkRowKey = this.$route.query.type || '-1';
      this.queryNewTypeList();
      this.queryNewsList();
    },
    watch: {
      '$route'() {
        this.queryNewsList();
      }
    }
  }
</script>

<style lang="scss" scoped>
  .news-ul {
    margin: 0;

    .news-list {
      margin-bottom: 10px;

      .news-title {
        font-size: 16px;

        &:hover {
          cursor: pointer;
          color: #409EFF;
        }
      }

      .news-time {
        padding-top: 6px;
        font-size: 12px;
        color: #757575;
        float: right;
      }

      .news-def {
        margin-top: 3px;
        font-size: 12px;
        color: #757575;

        .news-eye-star {
          float: right;
          margin-top: 3px;
        }
      }

      > p {
        margin: 0;
      }
    }
  }

  .showNewsTypeModal::v-deep .el-form-item__error {
    white-space: initial;
  }
</style>
